package org.wxy.sdk.util;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
/**
 * Created by wxy on 2018/05/27.
 *
 * @author wxy
 * @date on 2018/05/27 11:32
 */
public class RxUtil {
    public  static void delayed(final Runnable runnable, final int timeout) {
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                try {
                    Thread.sleep(timeout);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                subscriber.onNext(null);
            }
        }).subscribeOn(Schedulers.io()).observeOn(Schedulers.newThread()).subscribe(new Action1<Object>() {
            @Override
            public void call(Object t) {
                if (runnable != null) {
                    runnable.run();
                }
            }
        });
    }

    public static Subscription delayedOnMainThread(final Runnable runnable, final int time) {
        return Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                subscriber.onNext(null);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
                runnable.run();
            }
        });
    }
}
